package cn.tedu.charging.order;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@SpringBootTest
public class HW_RabbitMQ {

    private String directExchangeName = "test-add-exchange-0";
    private String fanoutExchangeName = "test-add-exchange-1";
    private String RoutingKeyName = "t-a-q";
    private String AllQueueName = "test-add-queue";

    @Test
    public void publishDirect() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(directExchangeName,BuiltinExchangeType.DIRECT);

        for (int i = 0; i < 3; i++) {
            String routingKey = RoutingKeyName + "-" + i;
            String queueName = AllQueueName + "-" + i;

            channel.queueDeclare(queueName,false,false,false,null);

            channel.queueBind(queueName,directExchangeName,routingKey);

            String message = "test" + i;
            channel.basicPublish(directExchangeName,routingKey,null,message.getBytes());
            System.out.println("direct消息已发送到RabbitMQ" + message);
        }
        channel.close();
        connection.close();
    }

    @Test
    public void publishFanout() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(fanoutExchangeName,BuiltinExchangeType.FANOUT);

        for (int i = 3; i < 6; i++) {
            String routingKey = RoutingKeyName + "-" + i;
            String queueName = AllQueueName + "-" + i;

            channel.queueDeclare(queueName,false,false,false,null);
            channel.queueBind(queueName,fanoutExchangeName,routingKey);

        }
        String message = "test";
        channel.basicPublish(fanoutExchangeName,"",null,message.getBytes());
        System.out.println("发送fanout消息到Rabbit"+ message);
        channel.close();
        connection.close();

    }

    private static ConnectionFactory getConnectionFactory(){
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        return connectionFactory;
    }
}
